package org.shoukaiseki.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Map;
import java.util.StringJoiner;

/**
 *
 **/
public class UrlUtils {

    public class ByteArrayBody{

        private byte[] data;
        private String filename;

        public byte[] getData() {
            return data;
        }

        public void setData(byte[] data) {
            this.data = data;
        }

        public String getFilename() {
            return filename;
        }

        public void setFilename(String filename) {
            this.filename = filename;
        }
    }


    public static final Logger logger= LoggerFactory.getLogger(UrlUtils.class);

    public static String formatUrlParam( Map<String,?> params)  {
        try{
            StringJoiner param=new StringJoiner("&","","");
            String[] keys = params.keySet().toArray(new String[0]);
            Arrays.sort(keys);
            for (String key : keys) {
                if(params.get(key)==null||StringUtils.isEmpty(params.get(key).toString())){
                    continue;
                }
                param.add(key+"="+ URLEncoder.encode(params.get(key).toString(), "UTF-8"));
            }
            return param.toString();
        }catch (Throwable t){
            throw new RuntimeException("",t);

        }
    }



//    public static byte[] readUrlBytes(String imgUrl){
//        boolean error=false;
//        InputStream inputstream=null;
//        HttpURLConnection uc=null;
//        byte[] bytes=null;
//        try{
//            URL url = new URL(imgUrl);
//            uc = (HttpURLConnection) url.openConnection();
//            uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true
//            uc.connect();
//            inputstream = uc.getInputStream();
//            bytes = inputstream.readAllBytes();
//        }catch (Throwable t){
//            logger.error("imgUrl="+imgUrl,t);
//        }finally {
//            if (inputstream!=null) {
//                try {
//                    inputstream.close();
//                } catch (IOException e) {
//                }
//                if (uc!=null) {
//                    uc.disconnect();
//                }
//            }
//        }
//        if(error){
//            throw new RuntimeException("读取文件出错"+imgUrl);
//        }
//        return bytes;
//    }

}
